import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../layout/Layout.vue'

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/dashboard/index.vue'),
        meta: { title: '仪表盘' }
      },
      {
        path: 'inventory',
        name: 'Inventory',
        redirect: '/inventory/list',
        meta: { title: '库存管理' },
        children: [
          {
            path: 'list',
            name: 'InventoryList',
            component: () => import('../views/inventory/list.vue'),
            meta: { title: '库存列表' }
          },
          {
            path: 'in',
            name: 'InventoryIn',
            component: () => import('../views/inventory/in.vue'),
            meta: { title: '入库管理' }
          },
          {
            path: 'out',
            name: 'InventoryOut',
            component: () => import('../views/inventory/out.vue'),
            meta: { title: '出库管理' }
          }
        ]
      },
      {
        path: 'purchase',
        name: 'Purchase',
        redirect: '/purchase/orders',
        meta: { title: '采购管理' },
        children: [
          {
            path: 'orders',
            name: 'PurchaseOrders',
            component: () => import('../views/purchase/orders.vue'),
            meta: { title: '采购订单' }
          },
          {
            path: 'suppliers',
            name: 'Suppliers',
            component: () => import('../views/purchase/suppliers.vue'),
            meta: { title: '供应商管理' }
          }
        ]
      },
      {
        path: 'system',
        name: 'System',
        redirect: '/system/users',
        meta: { title: '系统管理' },
        children: [
          {
            path: 'users',
            name: 'Users',
            component: () => import('../views/system/users.vue'),
            meta: { title: '用户管理' }
          },
          {
            path: 'roles',
            name: 'Roles',
            component: () => import('../views/system/roles.vue'),
            meta: { title: '角色管理' }
          }
        ]
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue'),
    meta: { title: '登录' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 获取token
  const token = localStorage.getItem('token')
  
  // 如果访问登录页面，直接放行
  if (to.path === '/login') {
    next()
    return
  }
  
  // 如果没有token，重定向到登录页
  if (!token) {
    next('/login')
    return
  }
  
  next()
})

export default router 